class LicensesController < ApplicationController
  def new
    @license = License.new
    @driver = Driver.find(params[:driver_id])
  end
  
  def create
    @driver = Driver.find(params[:driver_id])
    issued_date = Date.strptime(params[:license][:issued_date], "%d-%m-%Y")
    exp_date = Date.strptime(params[:license][:expiry_date], "%d-%m-%Y")
    
    params[:license][:issued_date] = issued_date
    params[:license][:expiry_date] = exp_date

    license = License.new(params[:license])

    license.driver_id = params[:driver_id]
    
    respond_to do |format|
      if license.save
        format.html  { redirect_to(licenses_driver_path(@driver),
                      :notice => 'License was added successfully for the driver.') }
        format.json  { render :json => @driver,
                      :status => :created, :location => @driver }
      else
        format.html  { render :action => "new" }
        format.json  { render :json => @driver.errors,
                      :status => :unprocessable_entity }
      end
    end
  end

  def edit
    @license = License.find(params[:id])
    @driver = Driver.find(params[:driver_id])
  end

  def update
    @driver = Driver.find(params[:driver_id])
    @license = License.find(params[:id])

    issued_date = Date.strptime(params[:license][:issued_date], "%d-%m-%Y")
    exp_date = Date.strptime(params[:license][:expiry_date], "%d-%m-%Y")

    params[:license][:issued_date] = issued_date
    params[:license][:expiry_date] = exp_date

    respond_to do |format|
      if @license.update_attributes(params[:license])
        format.html  { redirect_to(licenses_driver_path(@driver),
                      :notice => 'License was updated successfully for the driver.') }
        format.json  { render :json => @driver,
                      :status => :created, :location => @driver }
      else
        format.html  { render :action => "new" }
        format.json  { render :json => @driver.errors,
                      :status => :unprocessable_entity }
      end
    end
  end

  def destroy
    license = License.find(params[:id])
    License.destroy(license)

    respond_to do |format|
        format.html  { redirect_to(licenses_driver_path(@driver),
                      :notice => 'License was deleted successfully for the driver.') }
    end
  end
end
